import React, { useEffect, useState } from 'react';
import {
  Result,
  Skeleton,
  Tag,
  Empty,
  Button,
  Tooltip,
  Icon,
  Select,
  Divider,
  Radio,
  Modal,
} from 'antd';
import { connect } from 'dva';
import classNames from 'classnames';
import ScrollBar from '@/components/ScrollBar';
import styles from './index.less';
import request from '@/utils/request';
import SetCondition from './components/SetCondition';

const { CheckableTag } = Tag;
const { Option } = Select;

function Content(props) {
  // 状态 type:plan , type:rule
  const [status, setStatus] = useState('');
  // rule 与 plan 的接口数据
  const [data, setData] = useState({});
  // 请求状态
  const [loading, setLoading] = useState(false);
  // 归属环节选中
  const [selectedTags, setSelectedTags] = useState([]);
  // 业务类型选中
  const [selectedTags1, setSelectedTags1] = useState([]);
  // 保存记录type：rule 的模式 精简模式：simplify  操作模式：operate
  const [rulePattern, setRulePattern] = useState('simplify');
  //  设置条件、规则结果模态弹窗
  const [conditVisiable, setConditVisiable] = useState(false);
  //  设置条件、规则结果条件入参  set 表示为条件、rule 表示为规则结果
  const [conditStatus, setConditStatus] = useState('');

  useEffect(() => {
    if (!props.id) return;
    // 当前选中项的type:CurStatus及选中项Id：Curid
    const curStatus = props.id.match(/,(\S*)/)[1];
    const curId = props.id.match(/(\S*),/)[1];
    if (curStatus === 'plan') {
      setLoading(true);
      request('/oc/RuleCfgController/showPlanCond.do', {
        data: {
          plan_id: curId,
        },
      }).then(res => {
        setLoading(false);
        setData(res);
      });
    } else if (curStatus === 'rule') {
      setLoading(true);
      setRulePattern('simplify');
      request('/oc/RuleCfgController/showRuleCond.do', {
        data: {
          rule_id: curId,
        },
      }).then(res => {
        setLoading(false);
        setData(res);
      });
    }
    setStatus(curStatus);
  }, [props.id]);

  /**
   * 此模块为type:plan的逻辑模块
   * 涉及:归属环节、业务类型
   * 模块
   */

  // 归属环节标签点击事件
  const handleChange = (tag, checked) => {
    if (checked) {
      setSelectedTags([tag]);
    } else {
      setSelectedTags(['']);
    }
  };

  // 业务类型标签点击事件
  const handleChange1 = (tag, checked) => {
    if (checked) {
      setSelectedTags1([tag]);
    } else {
      setSelectedTags1(['']);
    }
  };
  // type：plan 的模板渲染
  const renderPlan = (
    <Skeleton active loading={loading}>
      <div className="ant-detail-title">归属环节</div>
      <div className={styles.radio}>
        {data.tache_list && data.tache_list.length > 0 ? (
          data.tache_list.map(tag => (
            <CheckableTag
              key={tag.traceId}
              checked={selectedTags.indexOf(tag) > -1}
              onChange={checked => handleChange(tag, checked)}
            >
              {tag.traceName}
            </CheckableTag>
          ))
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
        )}
      </div>

      <div className="ant-detail-title">业务类型</div>
      <div className={styles.radio}>
        {data.busiTypeList && data.busiTypeList.length > 0 ? (
          data.busiTypeList.map(tag => (
            <CheckableTag
              key={tag.attrValueId}
              checked={selectedTags1.indexOf(tag) > -1}
              onChange={checked => handleChange1(tag, checked)}
            >
              {tag.attrValueName}
            </CheckableTag>
          ))
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
        )}
      </div>
    </Skeleton>
  );

  /**
   * 此模块为type:rule 模块。
   * 涉及:精简模式 设置条件 规则结果
   */
  // 精简操作与操作模式的切换
  const rulePatternChange = e => {
    setRulePattern(e.target.value);
  };
  // 关闭设置条件弹窗
  const closeModal = () => {
    setConditVisiable(false);
  };

  // type：rule 的模板渲染
  const renderRule = (
    <Skeleton active loading={loading}>
      <div className="ant-detail-title">
        <span className="padding-right">设置条件</span>
        <Tooltip title="添加">
          <Icon
            type="plus-circle"
            className={styles.icon_hover}
            onClick={() => {
              setConditVisiable(true);
              setConditStatus('set');
            }}
          />
        </Tooltip>
        <Radio.Group
          className="pull-right"
          defaultValue="simplify"
          size="small"
          buttonStyle="solid"
          onChange={rulePatternChange}
        >
          <Radio.Button value="simplify">精简模式</Radio.Button>
          <Radio.Button value="operate">操作模式</Radio.Button>
        </Radio.Group>
      </div>
      <div className={styles.rule_form}>
        {data.cal_cond_list && data.cal_cond_list.length > 0 ? (
          data.cal_cond_list.map((tag, index) => (
            <>
              <div hidden={rulePattern === 'simplify'}>
                <Select
                  style={{ width: 100 }}
                  className="margin-bottom"
                  placeholder="请选择"
                  allowClear
                >
                  <Option value="(">(</Option>
                </Select>
              </div>
              <div style={{ paddingLeft: rulePattern === 'simplify' ? 0 : '100px' }}>
                <div className={styles.rule_title}>{tag[0].attr.attrName}</div>
                <div>
                  <Select style={{ width: 200 }} placeholder="请选择" allowClear>
                    {data.rule_cond_combobox.map(item => {
                      return (
                        <Option key={item.attrValueId} value={item.attrValueId}>
                          {item.attrValueName}
                        </Option>
                      );
                    })}
                  </Select>
                  <span className={classNames(styles.rule_tag)}>
                    {tag.map(i => (
                      <Tag key={i.attrValue}>{i.attrValueName}</Tag>
                    ))}
                  </span>
                </div>
              </div>
              <div hidden={rulePattern === 'simplify'}>
                <Select
                  style={{ width: 100 }}
                  className="margin-bottom"
                  placeholder="请选择"
                  allowClear
                >
                  <Option value=")">)</Option>
                </Select>
                {index + 1 < data.cal_cond_list.length ? (
                  <Select
                    style={{ width: 100, marginLeft: '8px' }}
                    className="margin-bottom"
                    placeholder="请选择"
                    allowClear
                  >
                    <Option value="OR">OR</Option>
                    <Option value="AND">ANT</Option>
                  </Select>
                ) : null}
              </div>
            </>
          ))
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
        )}
      </div>

      <Divider className="small" />

      <div className="ant-detail-title">
        <span className="padding-right">规则结果</span>
        <Tooltip title="添加">
          <Icon
            type="plus-circle"
            className={styles.icon_hover}
            onClick={() => {
              setConditVisiable(true);
              setConditStatus('rule');
            }}
          />
        </Tooltip>
      </div>
      <div className={styles.rule_form}>
        {data.final_cond_list && data.final_cond_list.length > 0 ? (
          data.final_cond_list.map(tag => (
            <>
              <div className={styles.rule_title}>{tag[0].attr.attrName}</div>
              <div className={classNames(styles.rule_tag)} style={{ marginLeft: 0 }}>
                {tag.map(i => (
                  <Tag key={i.attrValue}>{i.attrValueName}</Tag>
                ))}
              </div>
            </>
          ))
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
        )}
      </div>
    </Skeleton>
  );

  return (
    <div className={styles.right_scroll_content}>
      <ScrollBar autoHide autoHeight autoHeightMax={props.height - 110}>
        <div className={styles.right_content} style={{ height: props.height - 110 }}>
          {status === 'plan' ? renderPlan : null}
          {status === 'rule' ? renderRule : null}
          {status !== 'rule' && status !== 'plan' ? (
            <div className={styles.vertical_center}>
              <Result status="404" subTitle="该模块无配置区，请选择正确层级进行规则配置" />
            </div>
          ) : null}
        </div>
      </ScrollBar>
      <div
        style={{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
        }}
      >
        <Button type="primary">保存</Button>
      </div>

      {conditVisiable ? (
        <SetCondition visiable={conditVisiable} close={closeModal} status={conditStatus} />
      ) : null}
    </div>
  );
}

export default connect(({ ruleConfig }) => ({
  id: ruleConfig.id,
}))(Content);
